var common = require('../../../util/common');

module.exports = function(app) {
    return new Handler(app);
};

var Handler = function(app) {
    this.app = app;
    this.channelService = this.app.get('channelService');
    this.sceneId = this.app.getCurServer().scene;
    this.channel = this.channelService.getChannel('scene_' + this.sceneId, true);
    this.cachedb = this.app.get('cachedb');
    this.sceneCacheKey = 'scene_' + this.sceneId;
};

// 切换场景
Handler.prototype.changeScene = function(msg, session, next) {
    if (!session.uid) {
        next(null, {code: 500, msg: '请先登录'});
        return;
    }
    var channel = this.channel;
    var app = this.app;

    // 离开场景channel
    channel.leave(session.uid, session.frontendId);
    this.cachedb.asyncHdel(this.sceneCacheKey, 'player_' + session.uid);

    this.cachedb.asyncGet(session.uid, function(err, data) {
        var player = JSON.parse(data);
        var param = {
            route: 'onLeave',
            uid: player.uid,
            sid: player.sid
        };
        channel.pushMessage(param);
        var scene = session.get('scene') == 0 ? 1 : 0;
        app.rpc.scene.remoteHandler.join(scene, player, null);
        next(null, {code: 200, msg: '切换场景成功'});
    });
};

// 场景聊天
Handler.prototype.chat = function(msg, session, next) {
    var cachedb = this.cachedb;
    var channel = this.channel;
    common.launchFiber(function() {
        var data = cachedb.syncGet(session.uid);
        var player = JSON.parse(data);
        var param = {
            route: 'onChat',
            type: 2,
            msg: player.name + ': ' + msg.msg
        }
        channel.pushMessage(param);
        common.invokeCallback(next);
    });
};